package com.dora.optimistic.lock.service;

import com.dora.optimistic.lock.entity.User;
import com.dora.optimistic.lock.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户服务
 *
 * @author Clarence
 * @date 2024/02/25
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据id查询用户
     * @param id id
     * @return {@link User}
     */
    public User getUserById(Long id) {
        return userMapper.selectUserById(id);
    }

    /**
     * 更新用户信息，包括乐观锁的处理
     *
     * @param user 用户
     * @return boolean
     */
    @Transactional
    public boolean updateUser(User user) {
        User oldUser = userMapper.selectUserById(user.getId());
        if (oldUser == null) {
            throw new RuntimeException("User not found!");
        }
        // 判断版本号是否一致
        if (!oldUser.getVersion().equals(user.getVersion())) {
            throw new RuntimeException("Concurrent modification detected!");
        }
        // 更新用户信息，包括版本号
        int rowsAffected = userMapper.updateUser(user);
        if (rowsAffected != 1) {
            throw new RuntimeException("Failed to update user!");
        }
        return true;
    }
}
